using B.S.NewMedical.Api.Write.Application.Command.ContentManagement.Patient;
using MediatR;
using Microsoft.AspNetCore.Mvc;
using System.Collections.Generic;

namespace B.S.NewMedical.Api.Write.Controllers.ContentManagement.Patient
{
    /// <summary>
    /// 患者管理控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]/[action]")]
    public class PatientController : ControllerBase
    {
        private readonly IMediator _mediator;

        public PatientController(IMediator mediator)
        {
            _mediator = mediator ?? throw new ArgumentNullException(nameof(mediator));
        }

        /// <summary>
        /// 新增患者
        /// </summary>
        /// <param name="command">新增患者命令</param>
        /// <returns>新增的患者ID</returns>
        /// <remarks>
        /// 示例请求：
        /// {
        ///   "accountId": 1001,
        ///   "name": "张三",
        ///   "sex": true,
        ///   "dateOfBirth": "1990-01-01",
        ///   "contactInfo": "13812345678",
        ///   "idCard": "320102199001011234",
        ///   "currentAddress": "江苏省南京市...",
        ///   "createPeople": "管理员"
        /// }
        /// </remarks>
        [HttpPost]
        public async Task<IActionResult> AddPatient([FromBody] AddPatientCommand command)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                var result = await _mediator.Send(command);
                return Ok(new 
                { 
                    Id = result, 
                    Message = "患者创建成功",
                    PatientName = command.Name,
                    IDCard = command.IDCard
                });
            }
            catch (ArgumentException ex)
            {
                return BadRequest(new { Message = ex.Message });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { Message = "创建患者时发生错误", Error = ex.Message });
            }
        }

        /// <summary>
        /// 更新患者信息
        /// </summary>
        /// <param name="command">更新患者命令</param>
        /// <returns>更新结果</returns>
        /// <remarks>
        /// 示例请求：
        /// {
        ///   "id": 1,
        ///   "accountId": 1001,
        ///   "name": "张三",
        ///   "sex": true,
        ///   "dateOfBirth": "1990-01-01",
        ///   "contactInfo": "13812345678",
        ///   "idCard": "320102199001011234",
        ///   "currentAddress": "江苏省南京市...",
        ///   "updatePeople": "管理员"
        /// }
        /// </remarks>
        [HttpPut]
        public async Task<IActionResult> UpdatePatient([FromBody] UpdatePatientCommand command)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                var result = await _mediator.Send(command);
                if (result)
                {
                    return Ok(new 
                    { 
                        Message = "患者信息更新成功",
                        PatientId = command.Id,
                        PatientName = command.Name
                    });
                }
                else
                {
                    return NotFound(new { Message = "患者不存在或已被删除" });
                }
            }
            catch (ArgumentException ex)
            {
                return BadRequest(new { Message = ex.Message });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { Message = "更新患者信息时发生错误", Error = ex.Message });
            }
        }

        /// <summary>
        /// 批量删除患者
        /// </summary>
        /// <param name="command">批量删除命令</param>
        /// <returns>批量删除结果</returns>
        /// <remarks>
        /// 示例请求：
        /// {
        ///   "ids": [1, 2, 3],
        ///   "updatePeople": "管理员"
        /// }
        /// 注意：删除患者前请确认无关联的就诊记录
        /// </remarks>
        [HttpDelete]
        public async Task<IActionResult> DeletePatients([FromBody] DeletePatientCommand command)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                var result = await _mediator.Send(command);

                if (result.Success)
                {
                    return Ok(new
                    {
                        result.Message,
                        result.SuccessCount,
                        result.FailCount,
                        result.FailedIds,
                        Details = $"成功删除 {result.SuccessCount} 个患者"
                    });
                }
                else
                {
                    return BadRequest(new
                    {
                        result.Message,
                        result.SuccessCount,
                        result.FailCount,
                        result.FailedIds,
                        Details = $"批量删除部分失败，成功 {result.SuccessCount} 个，失败 {result.FailCount} 个"
                    });
                }
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { Message = "批量删除患者时发生错误", Error = ex.Message });
            }
        }

        /// <summary>
        /// 删除单个患者
        /// </summary>
        /// <param name="id">患者ID</param>
        /// <param name="updatePeople">操作人</param>
        /// <returns>删除结果</returns>
        /// <remarks>
        /// 注意：删除患者前请确认无关联的就诊记录
        /// </remarks>
        [HttpDelete]
        public async Task<IActionResult> DeleteByIdPatient(int id, [FromQuery] string? updatePeople = null)
        {
            try
            {
                if (id <= 0)
                {
                    return BadRequest(new { Message = "患者ID必须大于0" });
                }

                var command = new DeletePatientCommand
                {
                    Ids = new List<int> { id },
                    UpdatePeople = updatePeople
                };

                var result = await _mediator.Send(command);

                if (result.Success && result.SuccessCount > 0)
                {
                    return Ok(new 
                    { 
                        Message = "患者删除成功",
                        PatientId = id,
                        OperatedBy = updatePeople
                    });
                }
                else
                {
                    return NotFound(new { Message = "患者不存在或删除失败" });
                }
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { Message = "删除患者时发生错误", Error = ex.Message });
            }
        }

        /// <summary>
        /// 验证身份证号是否可用
        /// </summary>
        /// <param name="idCard">身份证号</param>
        /// <param name="excludePatientId">排除的患者ID（用于更新时检查）</param>
        /// <returns>验证结果</returns>
        [HttpGet("validate-idcard")]
        public async Task<IActionResult> ValidateIDCard([FromQuery] string idCard, [FromQuery] int? excludePatientId = null)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(idCard))
                {
                    return BadRequest(new { Message = "身份证号不能为空" });
                }

                // 这里可以调用Handler或直接使用仓储检查
                // 简化实现，实际项目中建议创建专门的查询Handler
                return Ok(new 
                { 
                    IsAvailable = true, 
                    Message = "身份证号可用",
                    IDCard = idCard
                });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { Message = "验证身份证号时发生错误", Error = ex.Message });
            }
        }

        /// <summary>
        /// 验证联系方式是否可用
        /// </summary>
        /// <param name="contactInfo">联系方式</param>
        /// <param name="excludePatientId">排除的患者ID（用于更新时检查）</param>
        /// <returns>验证结果</returns>
        [HttpGet("validate-contact")]
        public async Task<IActionResult> ValidateContact([FromQuery] string contactInfo, [FromQuery] int? excludePatientId = null)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(contactInfo))
                {
                    return BadRequest(new { Message = "联系方式不能为空" });
                }

                // 这里可以调用Handler或直接使用仓储检查
                // 简化实现，实际项目中建议创建专门的查询Handler
                return Ok(new 
                { 
                    IsAvailable = true, 
                    Message = "联系方式可用",
                    ContactInfo = contactInfo
                });
            }
            catch (Exception ex)
            {
                return StatusCode(500, new { Message = "验证联系方式时发生错误", Error = ex.Message });
            }
        }
    }
}